package com.app.shiro;

import com.app.dao.LoginDao;
import com.app.entity.Customer;
import com.app.entity.Permission;
import com.app.entity.Role;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xinjian.hu on 18-2-26.
 */
public class BaseRealm extends AuthorizingRealm {
    @Resource
    private LoginDao loginDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Role role = null;
        List<Permission> permissions = null;
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) super.getAvailablePrincipal(principals);
        Customer customer = loginDao.getUser(username);
        /** 角色授权 */
        if (null != customer) {
            role = loginDao.getRole(customer.getId());
            authorizationInfo.addRole(role.getRoleName());
        } else {
            throw new AuthorizationException();
        }
        /** 权限验证 */
        if (null != role) {
            permissions = loginDao.getPermissions(role.getId());
            Set<String> set = new HashSet<String>();
            if (null != permissions && !permissions.isEmpty()) {
                for (Permission permission : permissions) {
                    set.add(permission.getPermissionName());
                }
            }
            authorizationInfo.setStringPermissions(set);
        } else {
            throw new AuthorizationException();
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //对当前用户进行登录认证
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = (String) upToken.getPrincipal();
        Customer customer = loginDao.getUser(username);
        if (null == customer) {
            throw new AuthenticationException();
        }
        //user写入session
        Subject subject = SecurityUtils.getSubject();
        if (null == subject) {
            throw new AuthenticationException();
        }
        Session session = subject.getSession();
        session.setAttribute("customer", customer);
        return new SimpleAuthenticationInfo(customer.getUsername(), customer.getPassword(), getName());
    }
}
